<template>
    <div class="card_body">
        <span class="card_body_title">添加银行卡</span>
        <div class="card_body_content">
            <van-form @submit="onSubmit" label-align="center" colon>
                <van-cell-group>
                    <van-field v-model="formInfo.card_name" name="卡名" label="卡名" placeholder="卡名"
                        :rules="[{ required: true, message: '请填写卡名' }]" />
                    <van-field v-model="formInfo.initial_amount" type="number" name="卡余额" label="卡余额" placeholder="卡余额"
                        :rules="[{ required: true, message: '请填写卡余额' }]" />
                    <van-field name="uploader" label="卡头像" v-model="formInfo.card_avatar"
                        :rules="[{ required: true, message: '请上传卡头像' }]">
                        <template #input>
                            <van-uploader v-model="fileList" :after-read="afterRead" :max-count="1" />
                        </template>
                    </van-field>
                    <van-field name="uploader" label="卡颜色-one" v-model="formInfo.card_color"
                        :rules="[{ required: true, message: '请选择卡颜色' }]">
                        <template #input>
                            <ColorPicker v-model:color="formInfo.card_color" />
                        </template>
                    </van-field>
                </van-cell-group>
                <div style="margin: 16px;">
                    <van-button round block type="primary" native-type="submit">
                        提交
                    </van-button>
                </div>
            </van-form>
        </div>
    </div>
</template>

<script setup>
import { ref, reactive } from "vue"
const emits = defineEmits("successAdd");
import { addCardReq, uploadImg } from "@/api/index"
import { showToast } from "vant";
// 颜色选择器
import ColorPicker from '@/components/ColorPicker.vue'
const fileList = ref([
]);
// 表单信息
const formInfo = reactive({
    card_name: "",
    initial_amount: null,
    card_avatar: null,
    card_color: null
})
// 文件上传
const afterRead = (file) => {
    console.log(file, "上传");
    // 此时可以自行将文件上传至服务器
    const formData = new FormData();
    formData.append('file', file.file);
    uploadImg(formData).then(res => {
        console.log(res, "上传成功");
        const { data: { Location } } = res.data;
        formInfo.card_avatar = 'http://' + Location;
    })
}


// 提交表单
const onSubmit = async () => {
    const userInfo = localStorage.getItem("userInfo");
    const uid = JSON.parse(userInfo).id;
    const params = {
        ...formInfo,
        uid
    }
    const res = await addCardReq(params);
    if (res.status === 200) {
        emits("successAdd");
    } else {
        showToast("添加失败，请重试！")
    }
}
</script>

<style lang="scss" scoped>
.card_body {
    &_title {
        font-size: .359rem;
        font-weight: 600;
        color: #333333;
    }

    .card_body_content {
        margin-top: .3077rem
    }
}
</style>